import { NewsApi, NewsVO } from '@/api/school/news'
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { useRouter } from 'vue-router'
export const useNews = ({ toast }) => {
  const router = useRouter()
  const total = ref(0)
  const newsList = ref([])
  const queryParams = reactive({
    pageNo: 1,
    pageSize: 10
  })
  const loadmoreState: any = ref('loading')
  const loading = ref(false)
  const getNewsList = async (isInit = false) => {
    if (isInit) {
      queryParams.pageNo = 1
    }
    loading.value = true
    try {
      const data: any = await NewsApi.getNewsPage(queryParams)
      console.log(data)
      if (queryParams.pageNo > 1) {
        newsList.value = newsList.value.concat(data.list)
      } else {
        newsList.value = data.list
      }
      total.value = data.total
      if (newsList.value.length < total.value) {
        loadmoreState.value = 'loading'
      } else {
        loadmoreState.value = 'finished'
      }
      console.log(newsList.value, '---newsList.value')
    } catch (error) {
      console.log(error)

      // toast.warning(error)
      loadmoreState.value = 'error'
    } finally {
      loading.value = false
    }
  }

  const handleClickNews = (news: NewsVO) => {
    router.push(`news/detail??id=${news.id}`)
  }
  const handleReachBottom = () => {
    if (newsList.value.length < total.value) {
      loadmoreState.value = 'loading'
      queryParams.pageNo++
      getNewsList()
    } else {
      loadmoreState.value = 'finished'
    }
  }
  const getCategory = (itemData) => {
    const findItem = getStrDictOptions(DICT_TYPE.SCHOOL_NEWS_TYPE).find(
      (item) => item.value == itemData?.newsType
    )
    return findItem?.label || ''
  }
  return {
    newsList,
    total,
    queryParams,
    loadmoreState,
    handleClickNews,
    getNewsList,
    handleReachBottom,
    getCategory
  }
}
